﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.MonoRail.Framework;
using Castle.MonoRail.Framework.Filters;
using Castle.MonoRail.Framework.Helpers;
using StateTheater.Models;
using StateTheaterDataModel;


namespace StateTheater.Controllers
{
	public class AdController	: SmartDispatcherController
	{
		StateTheaterDataContext db;
		public Random RNG { get; set; }

		public AdController(StateTheaterDataContext db)
		{
			this.db = db;
		}

		public void Banner(int code)
		{
			RedirectToAdFromCode(code, 'V');
		}

		public void Link(int code)
		{
			RedirectToAdFromCode(code, 'C');
		}


		private void RedirectToAdFromCode(int code, char typ)
		{
			/*
			 * select @RT = @Code %  max(runningtotal) from ads  where active=1;

				select top 1 @ID = adid from ads where runningtotal  > @RT and active = 1 order by runningtotal asc;
				insert into adviews (adid, type) values (@ID, @typ);
				select @URL = case @typ when 'V' then imageurl else clickurl end  from ads where adid = @ID;
			 */

			var currentAds = (from a in db.Ads
							  where a.active
							  where a.startdate <= DateTime.Now && a.enddate >= DateTime.Now
							  select a).ToList();

			int total = currentAds.Aggregate(0, (cnt, ad) => cnt + ad.Weight);
			int target = code % total;

			var displayAd = currentAds.First(ad => (target -= ad.Weight) < 0);
			var view = new Adview() { AdID = displayAd.AdID, type = typ, viewdate=DateTime.Now };
			db.Adviews.InsertOnSubmit(view);
			db.SubmitChanges();

			Response.RedirectToUrl(typ == 'C' ? displayAd.ClickURL : displayAd.ImageURL);
		}

	}
}
